//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.Expressions
{
    class ColumnExpression: Expression
    {
        public ColumnExpression(Worksheet worksheet, string name)
        {
            Contract.Requires(worksheet != null);
            this.name = name;
            Worksheet = worksheet;
        }
        internal override Expression Transposed(Cell target)
        {
            throw new NotImplementedException();
        }

        public override IEnumerable<Expression> GetSubExpressions()
        {
            yield break;
        }
        public override Expression Offset(CellRelativeAddress a)
        {
            return this;
        }
        public readonly Worksheet Worksheet;
        private readonly string  name;
        public string  Name
        {
            get { return name; }
        }
        public override string GetText(TextContext context)
        {
            return "[" + Name + "]";
        }
        public override IEnumerable<IDependencyNode> GetPrecedents(EvaluationContext context)
        {
            yield return context.Worksheet.Workbook.NameManager.GetNameNode(Name);
           /* yield break;
            Range r = Worksheet.GetRange(Name);
            if (r != null)
                foreach (Cell c in r.GetNonEmptyCells())
                    yield return c;*/
        }

        protected override object GetObjectImp(EvaluationContext context)
        {
            Range r = Worksheet.GetRange(Name);
            if (r is SingleCellRange)
                return r.FirstCell;

            if (r == null)
                return Errors.NameError;
            return r;
        }
        public override object GetValue(EvaluationContext context)
        {
            object o = GetObject(context);
            if (o is Range)
            {
                Range r = (Range)o;
                if (r.ColumnSpan == 1)
                {
                    return r.Worksheet[context.Target.Row.Index, r.TopLeftCell.Column.Index].Value;
                }
                else if (r.RowSpan == 1)
                {
                    return r.Worksheet[r.TopLeftCell.Row.Index, context.Target.Column.Index].Value;
                }
                return Errors.ValueError;
            }
            if (o is Cell)
                return ((Cell)o).Value;
            return o;
        }

    }
}